package com.test.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.test.entity.News;
import com.test.R;

import java.util.List;


/**
 * @Author Musique
 * 2020/8/1
 */
public class NewsAdapter extends BaseAdapter {

    private List<News> listNew;
    private Context mContext;

    public NewsAdapter(List<News> listNew, Context mContext) {
        this.listNew = listNew;
        this.mContext = mContext;
    }


    @Override
    public int getCount() {
        return listNew.size();
    }

    @Override
    public Object getItem(int i) {
        return listNew.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }


    //    @Override
    //    public View getView(@LayoutRes int i, View convertView, ViewGroup parent) {
    //        // convertView = LayoutInflater.from(mContext).inflate(R.layout.listview_demo, parent, false);
    //        // ImageView img_icon = convertView.findViewById(R.id.img_icon); //获取图片
    //        TextView title = convertView.findViewById(R.id.tv_title);
    //        TextView content = convertView.findViewById(R.id.tv_content);
    //
    //
    //        // img_icon.setBackgroundResource(listNew.get(i).getAIcon());
    //        title.setText(listNew.get(i).getTitle());
    //        content.setText(listNew.get(i).getContent());
    //        return convertView;
    //    }

    /**
     * 资源优化
     */
    @Override
    public View getView(int i, View convertView, ViewGroup parent) {

        ViewHolder holder = new ViewHolder();
        // 加载listview_demo.xml文件（每次运行都要加载，浪费资源，因此如下）
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.listview_demo, parent, false);

            //holder.img = convertView.findViewById(R.id.img_icon);
            holder.title = convertView.findViewById(R.id.tv_title);
            holder.content = convertView.findViewById(R.id.tv_content);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        // holder.img.setBackgroundResource(listNew.get(i).getAIcon());
        holder.title.setText(listNew.get(i).getTitle());
        holder.content.setText(listNew.get(i).getContent());
        return convertView;
    }

    /**
     * 创建一个存储对象静态对象方法
     */
    public static class ViewHolder {
        ImageView img;
        TextView title, content;
    }
}
